<?php

namespace App\Http\Middleware;

use App\Models\ModuleConfig;
use App\Services\ConfigService;
use App\Services\PermissionService;
use Closure;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        //错误验证 session中site和module必须存在
        if (!site() || !module()) {
            return redirect()->route('site.site.index');
        }
        //载入站点配置
        app(ConfigService::class)->loadSiteConfig();
        app(ConfigService::class)->loadCurrentModuleConfig();


        if (user()->isSuperAdmin || site()->user_id == user('id')) {
            return $next($request);
        }

        //验证模块访问权限
        $status = app(PermissionService::class)->checkModuleAccess(site(), module()['name']);

        if ($status) {
            return $next($request);
        }
        return $this->redirect();
    }

    public function redirect()
    {
        return redirect()->route('site.site.index')->with('danger', '没有操作权');

    }
}
